package com.rzico.sbl.ui.report.depot

import android.graphics.Color
import android.widget.TextView
import com.github.mikephil.charting.data.BarEntry
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.formatter.IAxisValueFormatter
import com.github.mikephil.extend.CustomValueFormatter
import com.github.mikephil.extend.setChartValueSelectedListener
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityReportDepotDetailBinding
import com.rzico.sbl.model.DepotBarrelDate
import com.rzico.sbl.model.ManagerDate
import com.rzico.sbl.model.ManagerGoodsData
import com.rzico.sbl.other.*
import com.rzico.sbl.viewmodel.ReportDepotViewModel
import com.xinnuo.common.extend.condition
import com.xinnuo.common.extend.get
import com.xinnuo.common.extend.getExtra
import com.xinnuo.common.extend.oneClick
import com.xinnuo.common.helper.*
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.utils.showTimeRangeDialog

class ReportDepotDetailActivity : BaseActivity(R.layout.activity_report_depot_detail) {

    private val mBinding by lazy { ActivityReportDepotDetailBinding.bind(getRootView()) }

    private var mBeginDate = getBeforeDate(6)
    private var mEndDate = getTodayDate()

    // 桶数/订单
    private val mTotalList = ArrayList<DepotBarrelDate>()

    // 出库商品
    private val mOutList = ArrayList<ManagerGoodsData>()
    private val mOutRange = ArrayList<ManagerDate>()
    private var mBarrelOutSn = ""

    // 入库空桶
    private val mInList = ArrayList<ManagerGoodsData>()
    private val mInRange = ArrayList<ManagerDate>()
    private var mBarrelInSn = ""

    // 外品牌入库
    private val mOtherList = ArrayList<ManagerDate>()

    // 异常订单
    private val mErrorList = ArrayList<ManagerDate>()

    override fun getViewModel() = get<ReportDepotViewModel>()

    override fun initData() {
        initTitle(title = "库管详情", name = "近7天")

        initLayout()

        updateAllData()
    }

    private fun initLayout() {
        mBinding.also {
            it.depotBarrel.apply {
                initChart(
                    isCenterLabel = true,
                    isXGridLine = true,
                    isYGridLine = false,
                    xAxisMinimum = 0f,
                    yAxisMinimum = 0f,
                    xSpaceEntry = 50f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mTotalList.indices) ""
                    else
                        mTotalList[value.toInt()]
                            .date
                            .toFormat("yyyy-MM-dd", "M.d")
                }
            }

            it.depotOrder.apply {
                initChart(
                    isCenterLabel = true,
                    isXGridLine = true,
                    isYGridLine = false,
                    xAxisMinimum = 0f,
                    yAxisMinimum = 0f,
                    xSpaceEntry = 50f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mTotalList.indices) ""
                    else
                        mTotalList[value.toInt()]
                            .date
                            .toFormat("yyyy-MM-dd", "M.d")
                }
            }

            it.depotOut1.apply {
                initChart(
                    isLegend = false,
                    touchDistance = 10f,
                    xLabelAngle = -45f,
                    yAxisMinimum = 0f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mOutList.indices) ""
                    else mOutList[value.toInt()].name.run {
                        if (length > 4) "${substring(0, 3)}..." else this
                    }
                }

                // 添加点击事件
                setChartValueSelectedListener {
                    onValueSelected { entry, _ ->
                        val index = entry.x.toInt()

                        mBarrelOutSn = mOutList[index].sn
                        mBinding.depotOutTitle.text = mOutList[index].name
                        getGoodsRangeData()
                    }
                }
            }

            it.depotOut2.apply {
                initChart(
                    isLegend = false,
                    xLabelAngle = -45f,
                    yAxisMinimum = 0f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mOutRange.indices) ""
                    else mOutRange[value.toInt()].date.toFormat("yyyy-MM-dd", "M.d")
                }
            }

            it.depotIn1.apply {
                initChart(
                    isLegend = false,
                    touchDistance = 10f,
                    xLabelAngle = -45f,
                    yAxisMinimum = 0f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mInList.indices) ""
                    else mInList[value.toInt()].name.run {
                        if (length > 4) "${substring(0, 3)}..." else this
                    }
                }

                // 添加点击事件
                setChartValueSelectedListener {
                    onValueSelected { entry, _ ->
                        val index = entry.x.toInt()

                        mBarrelInSn = mInList[index].name
                        mBinding.depotInTitle.text = mInList[index].name
                        getBrandRangeData()
                    }
                }
            }

            it.depotIn2.apply {
                initChart(
                    isLegend = false,
                    xLabelAngle = -45f,
                    yAxisMinimum = 0f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mInRange.indices) ""
                    else mInRange[value.toInt()].date.toFormat("yyyy-MM-dd", "M.d")
                }
            }

            it.depotOther.apply {
                initChart(
                    isLegend = false,
                    xLabelAngle = -45f,
                    yAxisMinimum = 0f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mOtherList.indices) ""
                    else mOtherList[value.toInt()].date.toFormat("yyyy-MM-dd", "M.d")
                }
            }

            it.depotError.apply {
                initChart(yAxisMinimum = 0f)

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mErrorList.indices) ""
                    else mErrorList[value.toInt()].date.toFormat("yyyy-MM-dd", "M.d")
                }
            }
        }

        tvRight?.oneClick { text ->
            text as TextView

            getViewModel()
                .showDropTimeFilter(
                    context = getIContext(),
                    bottom = text,
                    list = getViewModel().mTimeCheckList
                ) { bean ->

                    (bean.id != "4")
                        .condition {
                            getViewModel().mTimeCheckList.last().name = "自定义时间"
                        }

                    when (bean.id) {
                        "1" -> {
                            mBeginDate = getBeforeDate(6)
                            mEndDate = getTodayDate()
                            text.text = "近7天"

                            updateAllData()
                        }
                        "2" -> {
                            mBeginDate = getFirstDate()
                            mEndDate = getEndDate()
                            text.text = "本月"

                            updateAllData()
                        }
                        "3" -> {
                            mBeginDate = getBeforeFirstDate()
                            mEndDate = getBeforeEndDate()
                            text.text = "上月"

                            updateAllData()
                        }
                        "4" -> {
                            showTimeRangeDialog(
                                minYearValue = 2021,
                                isCurrentDate = true,
                                isAfterLimited = true,
                                onResult = { start, end ->
                                    getViewModel()
                                        .mTimeCheckList
                                        .forEach { it.isChecked = false }

                                    getViewModel()
                                        .mTimeCheckList
                                        .last()
                                        .isChecked = true

                                    mBeginDate = start
                                    mEndDate = end
                                    text.text = "自定义时间"
                                    bean.name = "$mBeginDate ~ $mEndDate"

                                    updateAllData()
                                }
                            )
                        }
                    }
                }
        }
    }

    /**
     * 设置总数据图表数据
     */
    private fun setTotalChart() {
        mBinding.apply {
            depotBarrel.apply {
                if (mTotalList.none { it.d_b.intValue > 0 }
                    && mTotalList.none { it.c_b.intValue > 0 }) clear()
                else {
                    setGroupData(
                        entries = arrayListOf(
                            mTotalList.mapIndexed { index, data ->
                                BarEntry(
                                    index.toFloat(),
                                    data.d_b.floatValue
                                )
                            },
                            mTotalList.mapIndexed { index, data ->
                                BarEntry(
                                    index.toFloat(),
                                    data.c_b.floatValue
                                )
                            }
                        ),
                        colorList = getViewModel().barrelAllColor(),
                        labelList = listOf("出库", "入库"),
                        xFromValue = 0f,
                        formatter = CustomValueFormatter()
                    )
                }

                animateY(500)
            }

            depotOrder.apply {
                if (mTotalList.none { it.d_o.intValue > 0 }
                    && mTotalList.none { it.c_o.intValue > 0 }) clear()
                else {
                    setGroupData(
                        entries = arrayListOf(
                            mTotalList.mapIndexed { index, data ->
                                BarEntry(
                                    index.toFloat(),
                                    data.d_o.floatValue
                                )
                            },
                            mTotalList.mapIndexed { index, data ->
                                BarEntry(
                                    index.toFloat(),
                                    data.c_o.floatValue
                                )
                            }
                        ),
                        colorList = getViewModel().color5(),
                        labelList = listOf("出库", "入库"),
                        xFromValue = 0f,
                        formatter = CustomValueFormatter()
                    )
                }

                animateY(500)
            }
        }
    }

    /**
     * 设置所有商品出库
     */
    private fun setOutChart() {
        mBinding
            .depotOut1
            .apply {
                if (mOutList.isEmpty()) {
                    clear()
                    mBinding.depotOut2.clear()
                    mBinding.depotOutTitle.text = "暂无商品"
                } else {
                    setSingleData(
                        entries = mOutList.mapIndexed { index, data ->
                            BarEntry(index.toFloat(), data.quantity.toFloat())
                        },
                        colorList = getViewModel().brandColor(),
                        formatter = CustomValueFormatter()
                    )
                }

                animateY(500)
            }
    }

    /**
     * 设置单个商品出库
     */
    private fun setOutRangeChart() {
        mBinding
            .depotOut2
            .apply {
                setSingleData(
                    entries = mOutRange.mapIndexed { index, data ->
                        BarEntry(index.toFloat(), data.quantity.toFloat())
                    },
                    colorList = listOf(
                        getViewModel()
                            .brandColor()[
                                mOutList.indexOfFirst { it.sn == mBarrelOutSn } % 24
                        ]
                    ),
                    isHighlight = false,
                    formatter = CustomValueFormatter()
                )

                animateY(500)
            }
    }

    /**
     * 设置所有品牌入库
     */
    private fun setInChart() {
        mBinding
            .depotIn1
            .apply {
                if (mInList.isEmpty()) {
                    clear()
                    mBinding.depotIn2.clear()
                    mBinding.depotInTitle.text = "暂无系列"
                } else {
                    setSingleData(
                        entries = mInList.mapIndexed { index, data ->
                            BarEntry(index.toFloat(), data.quantity.toFloat())
                        },
                        colorList = getViewModel().brandColor(),
                        formatter = CustomValueFormatter()
                    )
                }

                animateY(500)
            }
    }

    /**
     * 设置单个品牌入库
     */
    private fun setInRangeChart() {
        mBinding
            .depotIn2
            .apply {
                setSingleData(
                    entries = mInRange.mapIndexed { index, data ->
                        BarEntry(index.toFloat(), data.quantity.toFloat())
                    },
                    colorList = listOf(
                        getViewModel()
                            .brandColor()[
                                mInList.indexOfFirst { it.name == mBarrelInSn } % 24
                        ]
                    ),
                    isHighlight = false,
                    formatter = CustomValueFormatter()
                )

                animateY(500)
            }
    }

    /**
     * 设置外品牌入库
     */
    private fun setOtherChart() {
        mBinding
            .depotOther
            .apply {
                if (mOtherList.none { it.quantity.intValue > 0 }) clear()
                else {
                    setSingleData(
                        entries = mOtherList.mapIndexed { index, data ->
                            BarEntry(index.toFloat(), data.quantity.toFloat())
                        },
                        colorList = listOf(getViewModel().barrelInColor()[1]),
                        isHighlight = false,
                        formatter = CustomValueFormatter()
                    )
                }

                animateY(500)
            }
    }

    /**
     * 设置异常订单曲线图数据
     */
    private fun setErrorChart() {
        mBinding
            .depotError
            .apply {
                if (mErrorList.none { it.quantity.doubleValue > 0 }) clear()
                else {
                    setSingleData(
                        entries = mErrorList.mapIndexed { index, data ->
                            Entry(
                                index.toFloat(),
                                data.quantity.floatValue
                            )
                        },
                        lineColor = Color.parseColor("#FF0000"),
                        labelColor = Color.parseColor("#FF0000"),
                        highColor = Color.parseColor("#FF0000"),
                        drawableFill = R.drawable.fade_ff0000_to_trans,
                        valueColor = Color.parseColor("#FF0000"),
                        formatter = CustomValueFormatter()
                    )
                }

                animateY(500)
            }
    }

    /**
     * 获取桶数/订单柱状图数据
     */
    private fun getTotalData() {
        getViewModel()
            .barrelTotal(
                adminId = intent.getExtra("adminId"),
                beginDate = mBeginDate,
                endDate = mEndDate,
                onSuccess = {
                    mTotalList.clear()
                    mTotalList.addItems(it)

                    setTotalChart()
                }
            )
    }

    /**
     * 获取所有商品出库
     */
    private fun getGoodsListData() {
        getViewModel()
            .goodsList(
                adminId = intent.getExtra("adminId"),
                beginDate = mBeginDate,
                endDate = mEndDate,
                onSuccess = { list ->
                    mOutList.clear()
                    mOutList.addItems(list)

                    if (mOutList.isNotEmpty()) {
                        if (mOutList.none { it.sn == mBarrelOutSn }) {
                            mBarrelOutSn = mOutList[0].sn
                            mBinding.depotOutTitle.text = mOutList[0].name
                        }
                        getGoodsRangeData()
                    }

                    setOutChart()
                }
            )
    }

    /**
     * 获取单个商品出库
     */
    private fun getGoodsRangeData() {
        getViewModel()
            .goodsRangeList(
                goodsSn = mBarrelOutSn,
                adminId = intent.getExtra("adminId"),
                beginDate = mBeginDate,
                endDate = mEndDate,
                onSuccess = {
                    mOutRange.clear()
                    mOutRange.addItems(it)

                    setOutRangeChart()
                }
            )
    }

    /**
     * 获取所有品牌入库
     */
    private fun getBrandListData() {
        getViewModel()
            .brandList(
                adminId = intent.getExtra("adminId"),
                beginDate = mBeginDate,
                endDate = mEndDate,
                onSuccess = { list ->
                    mInList.clear()
                    mInList.addItems(list)

                    if (mInList.isNotEmpty()) {
                        if (mInList.none { it.name == mBarrelInSn }) {
                            mBarrelInSn = mInList[0].name
                            mBinding.depotInTitle.text = mInList[0].name
                        }
                        getBrandRangeData()
                    }

                    setInChart()
                }
            )
    }

    /**
     * 获取单个品牌入库
     */
    private fun getBrandRangeData() {
        getViewModel()
            .brandRangeList(
                brand = mBarrelInSn,
                adminId = intent.getExtra("adminId"),
                beginDate = mBeginDate,
                endDate = mEndDate,
                onSuccess = {
                    mInRange.clear()
                    mInRange.addItems(it)

                    setInRangeChart()
                }
            )
    }

    /**
     * 获取外品牌入库
     */
    private fun getOtherData() {
        getViewModel()
            .otherList(
                adminId = intent.getExtra("adminId"),
                beginDate = mBeginDate,
                endDate = mEndDate,
                onSuccess = {
                    mOtherList.clear()
                    mOtherList.addItems(it)

                    setOtherChart()
                }
            )
    }

    /**
     * 获取异常订单
     */
    @Suppress("unused")
    private fun getErrorData() {
        getViewModel()
            .errorList(
                adminId = intent.getExtra("adminId"),
                beginDate = mBeginDate,
                endDate = mEndDate,
                onSuccess = {
                    mErrorList.clear()
                    mErrorList.addItems(it)

                    setErrorChart()
                }
            )
    }

    /**
     * 刷新所有数据
     */
    private fun updateAllData() {
        getTotalData()
        getGoodsListData()
        getBrandListData()
        getOtherData()
    }

}